import requests
import json
import pandas as pd
import os
import sys

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

EXCEL_FILE = "laixinjian.xlsx"
REQUEST_TIMEOUT = 300  # 设置请求超时时间为300秒（5分钟）

try:
    # 读取Excel文件
    df = pd.read_excel(EXCEL_FILE, sheet_name="Sheet1")
    
    # 遍历每一行数据
    for index, row in df.iterrows():
        # 准备请求数据
        test_data = {
            "bh": str(row["信访举报件编号"]),  # 确保编号为字符串类型
            "caseIntruction": str(row["原件描述"])  # 确保描述为字符串类型
        }

        print(f"\n处理第 {index + 1} 条数据:")
        print("发送请求数据:")
        print(json.dumps(test_data, ensure_ascii=False, indent=2))
        
        try:
            response = requests.post(
                "http://localhost:8000/api/getLetters",
                json=test_data,
                timeout=REQUEST_TIMEOUT  # 设置请求超时
            )
            
            # 检查响应状态码
            response.raise_for_status()
            
            # 尝试解析JSON响应
            try:
                result = response.json()
                print("\n响应状态码:", response.status_code)
                print("响应内容:")
                print(json.dumps(result, ensure_ascii=False, indent=2))
                
            except json.JSONDecodeError as e:
                print("JSON解析错误:", str(e))
                print("原始响应内容:", response.text)
                
        except requests.exceptions.Timeout:
            print(f"请求超时（{REQUEST_TIMEOUT}秒），跳过当前数据")
            continue
        except requests.exceptions.RequestException as e:
            print(f"请求错误: {str(e)}")
            continue
            
except FileNotFoundError:
    print(f"错误：找不到{EXCEL_FILE}文件")
except pd.errors.EmptyDataError:
    print("错误：Excel文件为空")
except Exception as e:
    print("其他错误:", str(e))
